<template>
  <div class="problem-solve-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-left">
        <span v-if="setId" class="nav-link" @click="handleBackToProblemSet">
          <el-icon><ArrowLeft /></el-icon>
          编程区
        </span>
        <span v-else class="nav-link" @click="router.push('/problem')">
          <el-icon><ArrowLeft /></el-icon>
          题库
        </span>
      </div>

      <div class="nav-center">
        <h2 class="problem-title-nav">{{ problem?.title || "加载中..." }}</h2>
      </div>

      <div class="nav-right" v-if="setId">
        <span class="nav-link" :class="{ disabled: !hasPrevProblem }">
          <el-icon><ArrowLeft /></el-icon>
          上一题
        </span>
        <span class="nav-link" :class="{ disabled: !hasNextProblem }">
          下一题
          <el-icon><ArrowRight /></el-icon>
        </span>
      </div>
    </div>

    <div class="solve-layout">
      <!-- 左侧：题目描述 -->
      <div class="problem-panel">
        <div class="panel-header">
          <h3 class="section-title">题目描述</h3>
        </div>

        <div class="panel-content">
          <!-- 题目标题和元信息 -->
          <div class="problem-header-info">
            <div class="title-row">
              <h2 class="problem-title">{{ problem?.title || "题目加载中..." }}</h2>
              <div class="title-stats">
                <span class="stat-item">
                  <el-icon><DataAnalysis /></el-icon>
                  分数 {{ problem?.totalScore || 100 }}
                </span>
                <span class="stat-item">
                  <el-icon><TrendCharts /></el-icon>
                  通过率: {{ problem?.acceptanceRate || 0 }}%
                </span>
              </div>
            </div>
            <div class="meta-row">
              <el-tag v-if="problem" :type="getDifficultyType(problem.difficulty)" size="small">
                {{ getDifficultyText(problem.difficulty) }}
              </el-tag>
              <el-tag v-if="problem?.category" type="info" size="small" effect="plain">
                {{ problem.category }}
              </el-tag>
            </div>
          </div>

          <!-- 题目描述 -->
          <div class="problem-section">
            <div class="section-content">
              {{ problem?.description || "加载中..." }}
            </div>
          </div>

          <!-- 输入格式 -->
          <div class="problem-section" v-if="problem?.inputDescription">
            <h4 class="section-title">输入格式:</h4>
            <div class="section-content">
              {{ problem.inputDescription }}
            </div>
          </div>

          <!-- 输出格式 -->
          <div class="problem-section" v-if="problem?.outputDescription">
            <h4 class="section-title">输出格式:</h4>
            <div class="section-content">
              {{ problem.outputDescription }}
            </div>
          </div>

          <!-- 输入样例 -->
          <div class="problem-section" v-if="problem?.sampleInput">
            <h4 class="section-title">输入样例:</h4>
            <pre class="sample-code">{{ problem.sampleInput }}</pre>
          </div>

          <!-- 输出样例 -->
          <div class="problem-section" v-if="problem?.sampleOutput">
            <h4 class="section-title">输出样例:</h4>
            <pre class="sample-code">{{ problem.sampleOutput }}</pre>
          </div>
        </div>
      </div>

      <!-- 右侧：代码编辑器 -->
      <div class="code-panel">
        <div class="panel-header">
          <h3 class="section-title">代码编辑</h3>
        </div>

        <CodeEditor
          ref="codeEditorRef"
          :problem-id="parseInt(route.params.id)"
          :initial-code="initialCode"
          :initial-language="'python'"
          :time-limit="problem?.timeLimit"
          :memory-limit="problem?.memoryLimit"
          @update-result="handleJudgeResult"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 在线编程解题页面
 * 职责：题目展示、代码编辑、判题结果显示
 */
import { computed, onMounted, onUnmounted, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import { ArrowLeft, ArrowRight, DataAnalysis, TrendCharts } from "@element-plus/icons-vue"
import { useProblemsStore } from "@/stores/modules/problem"
import { getDifficultyType } from "@/utils/business/problem/difficulty"
import { DIFFICULTY } from "@/constants/business"
import { info } from "@/utils/core/logger"
import { handleError } from "@/utils/core/error-handler"
import CodeEditor from "./components/codeEditor.vue"

// 路由和状态管理
const route = useRoute()
const router = useRouter()
const problemsStore = useProblemsStore()

// 响应式数据
const codeEditorRef = ref(null)
const isLoading = ref(false)

// 题目集ID（从URL query获取）
const setId = computed(() => (route.query.setId ? parseInt(route.query.setId) : null))

// 上一题/下一题（暂时禁用，后续实现）
const hasPrevProblem = computed(() => false)
const hasNextProblem = computed(() => false)

// 计算属性
const problem = computed(() => problemsStore.currentProblem)

// 初始代码模板
const initialCode = `def solution(s):
    """
    请在这里编写你的解题代码
    
    Args:
        s: 输入参数
    
    Returns:
        处理结果
    """
    # 示例：字符串反转
    return s[::-1]
`

// 工具方法
const getDifficultyText = difficulty => {
  return DIFFICULTY[difficulty?.toUpperCase()] || difficulty || "未知"
}

// 业务逻辑

// 获取题目详情
const fetchProblemDetail = async () => {
  if (!route.params.id) {
    handleError(new Error("题目ID无效"), {
      message: "题目ID无效",
      context: "ProblemSolve"
    })
    await router.push("/problemSet")
    return
  }

  try {
    isLoading.value = true
    const problemId = parseInt(route.params.id)

    if (isNaN(problemId) || problemId <= 0) {
      throw new Error("题目ID格式错误")
    }

    await problemsStore.getProblemById(problemId)

    if (!problemsStore.currentProblem) {
      throw new Error("题目不存在或已被删除")
    }
  } catch (error) {
    const errorMessage = error.response?.status === 404 ? "题目不存在或已被删除" : "获取题目详情失败，请稍后重试"

    handleError(error, {
      message: errorMessage,
      context: "ProblemSolve"
    })

    setTimeout(() => {
      router.push("/problemSet")
    }, 3000)
  } finally {
    isLoading.value = false
  }
}

// 处理判题结果
const handleJudgeResult = judgeResult => {
  // 开发环境记录判题结果
  if (import.meta.env.DEV) {
    info("判题结果:", judgeResult)
  }
}

// 返回题目集
const handleBackToProblemSet = () => {
  if (setId.value) {
    router.push(`/problemSet/${setId.value}`)
  }
}

// 页面清理逻辑
const cleanup = () => {
  problemsStore.resetCurrentProblem()
}

// 生命周期
onMounted(() => {
  fetchProblemDetail()
})

onUnmounted(() => {
  cleanup()
})
</script>

<style scoped lang="scss">
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;

.problem-solve-container {
  height: 100vh;
  background: $bg-color-layout;
  display: flex;
  flex-direction: column;
}

.top-nav {
  background: white;
  border-bottom: 1px solid $border-color-light;
  padding: 12px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  flex-shrink: 0;

  .nav-left {
    flex-shrink: 0;

    .nav-link {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
      color: $color-primary;
      cursor: pointer;
      transition: opacity 0.2s;

      &:hover {
        opacity: 0.8;
      }

      &.disabled {
        color: $color-text-disabled;
        cursor: not-allowed;
      }
    }
  }

  .nav-center {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 0;
    padding: 0 20px;

    .problem-title-nav {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: $color-text-primary;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 600px;
    }
  }

  .nav-right {
    flex-shrink: 0;
    display: flex;
    gap: 16px;

    .nav-link {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
      color: $color-text-secondary;
      cursor: pointer;
      transition: color 0.2s;

      &:hover:not(.disabled) {
        color: $color-primary;
      }

      &.disabled {
        color: $color-text-disabled;
        cursor: not-allowed;
      }
    }
  }
}

.solve-layout {
  flex: 1;
  display: flex;
  height: calc(100vh - 60px - 50px);
  width: 100%;
  background: white;
  overflow: hidden;
}

.problem-panel {
  width: 50%;
  border-right: 1px solid $border-color-light;
  display: flex;
  flex-direction: column;
  background: $bg-color-white;
  overflow: hidden;
}

.code-panel {
  width: 50%;
  display: flex;
  flex-direction: column;
  background: $bg-color-white;
  overflow: hidden;
}

.panel-header {
  padding: 12px 20px;
  border-bottom: 1px solid $border-color-light;
  background: $bg-color-layout;
  flex-shrink: 0;

  .section-title {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: $color-text-primary;
  }
}

.panel-content {
  flex: 1;
  padding: 20px 24px;
  overflow-y: auto;

  .problem-header-info {
    margin-bottom: 24px;

    .title-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .problem-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: $color-text-primary;
        line-height: 1.4;
        flex: 1;
      }

      .title-stats {
        display: flex;
        align-items: center;
        gap: 16px;
        flex-shrink: 0;
        margin-left: 16px;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          color: $color-text-secondary;
          white-space: nowrap;
        }
      }
    }

    .meta-row {
      display: flex;
      align-items: center;
      gap: 8px;
      padding-top: 12px;
      border-top: 1px solid $border-color-lighter;
    }
  }

  .problem-section {
    margin-bottom: 20px;

    .section-title {
      margin: 0 0 10px 0;
      font-size: 16px;
      font-weight: 600;
      color: $color-text-primary;
    }

    .section-content {
      line-height: 1.8;
      color: $color-text-primary;
      font-size: 14px;
      white-space: pre-wrap;
    }

    .sample-code {
      background: $bg-color-layout;
      border: 1px solid $border-color-lighter;
      border-radius: 4px;
      padding: 12px 16px;
      font-family: "Consolas", "Monaco", "Courier New", monospace;
      font-size: 13px;
      color: $color-text-primary;
      margin: 0;
      white-space: pre-wrap;
      line-height: 1.6;
      overflow-x: auto;
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .top-nav {
    .nav-center {
      .problem-title-nav {
        max-width: 300px;
      }
    }
  }

  .solve-layout {
    flex-direction: column;
    height: auto;
    min-height: calc(100vh - 60px - 50px);
  }

  .problem-panel,
  .code-panel {
    width: 100%;
  }

  .problem-panel {
    height: auto;
    min-height: 400px;
    border-right: none;
    border-bottom: 1px solid $border-color-light;
  }

  .code-panel {
    height: auto;
    min-height: 500px;
  }
}

@media (max-width: 768px) {
  .problem-solve-container {
    height: auto;
    min-height: 100vh;
  }

  .top-nav {
    padding: 8px 16px;
    height: auto;

    .nav-center {
      display: none;
    }

    .nav-right {
      gap: 8px;
    }
  }

  .panel-header {
    padding: 10px 16px;
  }

  .panel-content {
    padding: 16px;
  }
}
</style>
